<?php

namespace common\services\myhtsq;


use common\services\BaseService;
use common\repositories\myhtsq\ContractRevenueRepository;
use common\repositories\myhtsq\RevenueRecognitionRepository;
use common\support\OSS;
use common\support\LogHelper;
use common\repositories\myhtsq\ErpUserRepository;



/**
 * Description of RevenueService
 * 收入管理服务
 * @author zhoud01
 */
class RevenueService extends BaseService
{

    public $_errorLog;
    private static $sheetIndex = 0;
    protected $_contractRevenueRepository;
    protected $_revenueRecognitionRepository;
    const UN_RECOGNIZED_REVENUE = "unrecognized"; //本期待确认收入
    const RECOGNIZED_REVENUE = "recognized";//本期已确认收入
    const CONTRACT_REVENUE = "contract";//合同收入
    const CLOSED_REVENUE = "closed";//合同收入

    public function __construct(contractRevenueRepository $contractRevenueRepository,revenueRecognitionRepository $revenueRecognitionRepository,$config = [])
    {
        $this->_contractRevenueRepository = $contractRevenueRepository;
        $this->_revenueRecognitionRepository = $revenueRecognitionRepository;

        $logConfig = [
            'logFile' => \Yii::$app->getRuntimePath() . '/logs/base/contract.log', // 日志文件路径配置
        ];
        $this->_errorLog = new LogHelper($logConfig);

        parent::__construct($config);
    }

    /**
     * 获取当前租期
     * @return array
     */
    public function getRecognitionDate()
    {
        return $this->_revenueRecognitionRepository->getRecognitionDate();
    }

    /**
     * 获取当前租期
     * @return array
     */
    public function getRecognitionDateNew()
    {
        return $this->_revenueRecognitionRepository->getRecognitionDateNew();
    }

    public function getRecognitionListDate()
    {
        return $this->_revenueRecognitionRepository->getRecognitionListDate();
    }

    /**
     *
     * @return boolean|string 失败返回false，成功返回收入期Id
     */
    public function setRecognitionDate($revenueRecognitionModel)
    {
        return $this->_revenueRecognitionRepository->setRecognitionDate($revenueRecognitionModel);
    }

    /**
     * 获取所有未关闭收入
     * @return array
     */
    public function getIsNotClosedRevenueAll()
    {
        return $this->_contractRevenueRepository->getIsNotClosedRevenueAll();
    }

    /**
     * 按照租期确认收入
     * @param string $recognitionBegin
     * @param string $recognitionEnd
     * @param string $isNotClosedRevenueAllParams
     * @return array
     */
    public function revenueRecognitionByDate($revenueList)
    {
        return $this->_revenueRecognitionRepository->revenueRecognitionRecordByPeriods($revenueList);
    }

    public function getRecognitionList($revenueId)
    {
        $getRecognitionDateNew = self::getRecognitionDateNew();
        return $this->_revenueRecognitionRepository->getRecognitionList($revenueId,$getRecognitionDateNew['recognition_begin'],$getRecognitionDateNew['recognition_end']);
    }

    /**
     * 增值服务一次性确认
     * @param $revenueList
     * @return array
     */
    public function revenueRecognitionByDisposable($revenueList)
    {
        return $this->_revenueRecognitionRepository->revenueRecognitionRecordByDisposables($revenueList);
    }

    /**
     * 广告按照一次性确认
     * @param $revenueList
     * @return array
     */
    public function revenueRecognitionByAd($revenueList)
    {
        return $this->_revenueRecognitionRepository->revenueRecognitionRecordByAd($revenueList);
    }

    public function revenueRecognitionAll($revenueList){
        return $this->_revenueRecognitionRepository->revenueRecognitionRecordAll($revenueList);
    }


    /**
     * 收入查询服务：获取收入列表信息，支持分页
     * @param string $searchKey 查询关键字
     * @param int $pageIndex 页索引
     * @param int $pageSize 页大小
     * @param string $beginDate 收入开始时间
     * @param string $endDate 收入结束时间
     * @param string $establishDate 收入开通时间
     * @param int $closeStatus 收入关闭状态
     * @return array PageResult
     */
    public function getRevenueListByPage($revenueModel)
    {
        return $this->_contractRevenueRepository->getRevenueListByPage($revenueModel);
    }

    public function exportRevenueList($revenueModel)
    {
        return $this->_contractRevenueRepository->exportRevenueList($revenueModel);
    }

    /**
     * 收入查询服务：获取收入列表信息，支持分页
     * @param string $searchKey 查询关键字
     * @param int $pageIndex 页索引
     * @param int $pageSize 页大小
     * @param string $beginDate 收入开始时间
     * @param string $endDate 收入结束时间
     * @param string $establishDate 收入开通时间
     * @param int $closeStatus 收入关闭状态
     * @return array PageResult
     */
    public function getRecognitionRevenueContractPageByDate($revenueRecognitionModel)
    {
        $result = $this->_revenueRecognitionRepository->getRecognitionRevenueContractByDate($revenueRecognitionModel);
        return $this->_revenueRecognitionRepository->getRecognitionRevenueContractPageByDate($result,$revenueRecognitionModel->pageIndex,$revenueRecognitionModel->pageSize);
    }

    public function getRecognitionRevenueContractByDate($revenueRecognitionModel)
    {
        return $this->_revenueRecognitionRepository->getRecognitionRevenueContractByDate($revenueRecognitionModel);
    }

    public function getRevenueReceivablePaymentListByDate($revenueRecognitionModel)
    {
        return $this->_revenueRecognitionRepository->getRevenueReceivablePaymentListByDate($revenueRecognitionModel);
    }

    public function getRecentRecognitionUser(){
        return $this->_revenueRecognitionRepository->getRecentRecognitionUser();
    }

    /**
     * 依据收入id查询确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public function getRecognitionLastUnionThisIssueByRevenueId($revenueId)
    {
        return $this->_revenueRecognitionRepository->getRecognitionLastUnionThisIssueByRevenueId($revenueId);
    }

    public function saveRecognitionByRevenueId($revenueRecognitionModel)
    {
        return $this->_revenueRecognitionRepository->addRevenueRecognition($revenueRecognitionModel);
    }

    /**
     * 修改结转收入
     * @param string $revenueId 收入ID
     * @return boolean|string 失败返回false，成功返回发票Id
     */
    public function updateRevenueRecognition($revenueRecognitionModel)
    {
        return $this->_revenueRecognitionRepository->updateRevenueRecognition($revenueRecognitionModel);
    }

    public function getRecognitionByRecognitionId($recognitionId)
    {
        return $this->_revenueRecognitionRepository->getRecognitionByRecognitionId($recognitionId);
    }

    public function delRevenueByRevenueId($revenueId)
    {
        return $this->_contractRevenueRepository->deleteRevenue($revenueId);
    }

    public function updateCloseStatusRevenueByRevenueId($revenueId,$type){
        return $this->_contractRevenueRepository->closeRevenueByRevenueId($revenueId,$type);//自动关闭收入项
    }

    public function getRevenueByRevenueId($revenueId)
    {
        return $this->_contractRevenueRepository->getRevenueByRevenueId($revenueId);
    }

    public function getRevenueRecognitionListByRevenueId($revenueId)
    {
        return $this->_revenueRecognitionRepository->getRevenueRecognitionListByRevenueId($revenueId);
    }

    /**
     * 获取当前活动表格
     * @param \PHPExcel $objPHPExcel
     * @return \PHPExcel_Worksheet
     */
    private static function getActiveSheet($objPHPExcel)
    {
        if (self::$sheetIndex == 0) {
            $objPHPExcel->setActiveSheetIndex(self::$sheetIndex);
            $activeSheet = $objPHPExcel->getActiveSheet();
        } else {
            $activeSheet = $objPHPExcel->createSheet(self::$sheetIndex);
        }
        self::$sheetIndex++;
        return $activeSheet;
    }

    /**
     * 导出合同
     * @param null $status
     * @param boolean $property 合同性质
     * @param string $keyword 关键字
     * @param integer $areaId 区域id
     * @param null $signPeopleId
     * @param int $timeType
     * @param string $timeStart
     * @param string $timeEnd
     * @param array $reportType
     * @return array
     * @internal param string $beginDate 结算开始时间
     * @internal param string $endDate 结算结束时间
     */
    public function exportRevenue($revenueRecognitionModel)
    {
        $userGuid = \Yii::$app->user->identity->userguid;
        $prefix = 'revenueExl';
        $cachekey = $prefix.$userGuid;

        $get = \Yii::$app->cache->get($cachekey);
        if(!empty($get)){
            return 'Excel导出中等待邮件发送,请不要重复点击!';//防止重复点击
        }else {
            \Yii::$app->cache->set($cachekey,'waiting',36000);
            $params = [
                'data'=>'Excel导出中等待邮件发送',//初次导出Excle
                'retCode'=>0,
            ];
            echo json_encode($params);//开始导出
        }

        fastcgi_finish_request();

        $objPHPExcel = new \PHPExcel();

        $this->makeExcel($objPHPExcel,$revenueRecognitionModel);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $fileName = sprintf("revenue-data_%s.xls", \Yii::$app->user->identity->userguid);
        $path = \Yii::getAlias("@mybackend/web/xls/");
        // 文件名称
        if (!is_dir($path)) {
            $mkResult = mkdir($path, 0755);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";mkResult=" . $mkResult . ";LINE=" . __LINE__);
        }

        $filepath = $path . $fileName;
        $objWriter->save($filepath); //脚本方式运行，保存在当前目录
        $key = $fileName;
        OSS::upload($key, $filepath);
        $ossUrl = OSS::getUrl($key);

        $user = ErpUserRepository::getUserById($userGuid);
        $this->sendMail($user['Email'],'收入导出Excel',$ossUrl);

        \Yii::$app->cache->delete($cachekey);//清除key

        $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";uploadResult=" . $ossUrl . ";LINE=" . __LINE__);
        return $ossUrl;
    }

    public function sendMail($to = 'zhoud01@mingyuanyun.com', $title = 'hello world',  $msg ='test from yii')
    {
        $prefix = "\n收入导出Excel下载链接"."\n";
        $mail = \Yii::$app->mailer->compose();
        $mail->setTo($to);
        $mail->setSubject($title);
        $mail->setHtmlBody($prefix.'<b>'.$msg.'</b>');
        $mail->send();
    }

    //Excel 制作调度
    private function makeExcel($objPHPExcel,$revenueRecognitionModel)
    {
        $file_desc = [];
        //1.本期待确认收入
        if (self::UN_RECOGNIZED_REVENUE === $revenueRecognitionModel->type) {
            $this->exportUnrecognizedRevenue($objPHPExcel,$revenueRecognitionModel);
            $file_desc[] = '本期待确认收入';
        }

        //2.本期已确认收入
        if (self::RECOGNIZED_REVENUE === $revenueRecognitionModel->type) {
            $this->exportRecognizedRevenue($objPHPExcel,$revenueRecognitionModel);
            $file_desc[] = '已确认收入';
        }

        //3.合同收入
        if (self::CONTRACT_REVENUE === $revenueRecognitionModel->type) {
            $this->exportContractRevenue($objPHPExcel,$revenueRecognitionModel);
            $file_desc[] = '合同收入';
        }

        //4.关闭收入
        if (self::CLOSED_REVENUE === $revenueRecognitionModel->type) {
            $this->exportClosedRevenue($objPHPExcel,$revenueRecognitionModel);
            $file_desc[] = '关闭收入';
        }

        $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__. ";Report=" . implode(',', $file_desc));
    }

    /**
     * 导出本期待确认收入列表导出
     * @param $objPHPExcel
     * @param $revenueRecognitionModel
     */
    public function exportUnrecognizedRevenue($objPHPExcel,$revenueRecognitionModel)
    {
        $data = $this->exportRevenueList($revenueRecognitionModel);
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('本期已确认收入');

        //设置列标题
        $columnTitles = ['签约客户', '收入项编号', '合同编号', '收入项名称', '收入确认方式', '收入项金额', '收入开始日期',
            '权益日期起始时间', '权益日期终止时间','已确认收入', '待确认收入', '未确认收入已发生坏账', '收入来源',
        ];

        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(15);
            $activeSheet->getStyle($columnIndex . '1')->getFont()->setBold(true);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = '2';
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //1.合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_code']);//2.收入编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']);//3.合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['finance_type_name']);//4.收入项名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['recognition_type']);//5.收入确认方式
                $i++;
                $activeSheet->setCellValue($i . $j, $val['amount']);//6.收入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['establish_time']);//7.收入开始日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['begin_on']);//8.权益日期开始
                $i++;
                $activeSheet->setCellValue($i . $j, $val['end_on']);//9.权益日期结束
                $i++;
                $activeSheet->setCellValue($i . $j, $val['total_revenue_recognition_amount']);//10.已确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_unrecognized_amount']);//11.待确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['unrecognized_bad_debt_amount']);//12.未确认收入已发生坏账
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_source']);//13.收入来源
                $j++;
            }
        }
    }

    /**
     * 导出本期已确认收入列表导出
     * @param $objPHPExcel
     * @param $revenueRecognitionModel
     */
    public function exportRecognizedRevenue($objPHPExcel,$revenueRecognitionModel)
    {
        $data = $this->exportRevenueList($revenueRecognitionModel);
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('本期已确认收入');

        //设置列标题
        $columnTitles = ['签约客户', '收入项编号', '合同编号', '收入项名称', '收入确认方式', '收入项金额', '收入开始日期',
            '权益日期起始时间', '权益日期终止时间', '上期累计确认收入', '本期确认收入', '待确认收入', '是否关闭', '收入来源',
        ];

        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(15);
            $activeSheet->getStyle($columnIndex . '1')->getFont()->setBold(true);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = '2';
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //1.签约客户
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_code']);//2.收入编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']);//3.合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['finance_type_name']);//4.收入项名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['recognition_type']);//5.收入确认方式
                $i++;
                $activeSheet->setCellValue($i . $j, $val['amount']);//6.收入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['establish_time']);//7.收入开始日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['begin_on']);//8.权益日期开始
                $i++;
                $activeSheet->setCellValue($i . $j, $val['end_on']);//9.权益日期结束
                $i++;
                $activeSheet->setCellValue($i . $j, $val['last_total_revenue_recognition_amount']);//10.上期累计确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['this_recognition_amount']);//11.本期确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_unrecognized_amount']);//12.待确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_close_status']);//13.已确认收入发生坏账
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_source']);//14.收入来源
                $j++;
            }
        }
    }

    public function exportContractRevenue($objPHPExcel,$revenueRecognitionModel)
    {
        $data = $this->exportRevenueList($revenueRecognitionModel);
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('合同收入');

        //设置列标题
        $columnTitles = ['合同编号', '签约客户', '合同编号', '录入日期', '签约金额', '应结算金额', '已确认收入金额',
            '待确认收入金额', '累计开票金额', '累计回款金额',
        ];

        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(15);
            $activeSheet->getStyle($columnIndex . '1')->getFont()->setBold(true);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = '2';
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['contract_code']);//1.合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //2.签约客户
                $i++;
                $activeSheet->setCellValue($i . $j, $val['property_name']);//3.合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['input_date']);//4.录入日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_amount']);//5.签约金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_amount']);//6.应结算金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['total_revenue_recognition_amount']);//7.已确认收入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_unrecognized_amount']);//8.待确认收入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['total_invoice_amount']);//9.累计开票金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['total_payment_amount']);//10.累计回款金额
                $j++;
            }
        }
    }

    public function exportClosedRevenue($objPHPExcel,$revenueRecognitionModel)
    {
        $data = $this->exportRevenueList($revenueRecognitionModel);
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('关闭收入');

        //设置列标题
        $columnTitles = ['财务收入项', '确认方式', '收入项编码', '结转开始日期', '权益日期开始', '权益日期结束', '收入金额',
            '累计已确认金额', '未确认金额', '未确认收入已发生坏账',
        ];

        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(15);
            $activeSheet->getStyle($columnIndex . '1')->getFont()->setBold(true);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = '2';
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['finance_type_name']);//1.财务收入项
                $i++;
                $activeSheet->setCellValue($i . $j, $val['recognition_type']); //2.确认方式
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_code']);//3.收入项编码
                $i++;
                $activeSheet->setCellValue($i . $j, $val['establish_time']);//4.结转开始日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['begin_on']);//5.权益日期开始
                $i++;
                $activeSheet->setCellValue($i . $j, $val['end_on']);//6.权益日期结束
                $i++;
                $activeSheet->setCellValue($i . $j, $val['amount']);//7.收入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['total_revenue_recognition_amount']);//8.累计已确认金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_unrecognized_amount']);//9.未确认金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['unrecognized_bad_debt_amount']);//10.未确认收入已发生坏账
                $j++;
            }
        }
    }


}
